package com.kedsoft.docms.controller;

import com.kedsoft.docms.common.CommonResult;
import com.kedsoft.docms.entity.User;
import com.kedsoft.docms.mapper.UserMapper;
import com.kedsoft.docms.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2018-11-08
 */
@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value="/login", method = {RequestMethod.GET})
    public String login(){
        return "sys/login";
    }

    @RequestMapping(value="/doLogin", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult<User> doLogin(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password){
        Map<String, Object> param = new HashMap<>();
        param.put("username",username);
        param.put("password", MD5Utils.getMD5String(password));
        System.out.println("username="+username+" password="+MD5Utils.getMD5String(password));
        List<User> list = userMapper.selectByMap(param);
        if(list!=null && list.size()>0){
            request.getSession().setAttribute("loginUser",list.get(0));
            return new CommonResult<User>("200","用户登录成功",list.get(0));
        }
        return new CommonResult<User>("400","用户名或密码错误",null);
    }

    @RequestMapping(value = "/doLogout", method = {RequestMethod.GET})
    public String doLogout(HttpServletRequest request){
        request.getSession().setAttribute("loginUser",null);
        request.getSession().removeAttribute("loginUser");
        return "redirect:/login.html";
    }

}
